
function createMinuteAlarm() {
  const now = new Date();
  const seconds = now.getSeconds();
  const delayInSeconds = 60 - seconds;
  const delayInMinutes = delayInSeconds / 60;

  chrome.alarms.create("MinuteAlarm", { 
    delayInMinutes: delayInMinutes, 
    periodInMinutes: 1 
  });
}

createMinuteAlarm();

chrome.alarms.onAlarm.addListener(function(alarm) {
  if (alarm.name != "MinuteAlarm") return;

  schedule(new Date()) //需要外部实现该接口
});

function corn(expr, taskName, callback) {
  if (isCronMatch(expr)) {
    callback(new Date());
  }
}

function isCronMatch(cronExpr) {
  const now = new Date();
  const minute = now.getMinutes();
  const hour = now.getHours();
  const date = now.getDate();
  const month = now.getMonth() + 1;
  const dayOfWeek = now.getDay();

  const [cronMinute, cronHour, cronDate, cronMonth, cronDayOfWeek] = cronExpr.split(' ');

  return isFieldMatch(minute, cronMinute) &&
         isFieldMatch(hour, cronHour) &&
         isFieldMatch(date, cronDate) &&
         isFieldMatch(month, cronMonth) &&
         isFieldMatch(dayOfWeek, cronDayOfWeek === '7' ? '0' : cronDayOfWeek);
}

function isFieldMatch(value, field) {
  if (field === '*') {
    return true;
  }
  if (field.includes('/')) {
    const [range, step] = field.split('/');
    const stepValue = parseInt(step, 10);
    if (range === '*') {
      return value % stepValue === 0;
    } else if (range.includes('-')) {
      const [start, end] = range.split('-').map(Number);
      if (value >= start && value <= end) {
        return (value - start) % stepValue === 0;
      }
      return false;
    }
  }
  if (field.includes('-')) {
    const [start, end] = field.split('-').map(Number);
    return value >= start && value <= end;
  }
  if (field.includes(',')) {
    return field.split(',').map(Number).includes(value);
  }
  return Number(field) === value;
}
